<template>
  <div class="payment-container">
    <el-card class="payment-card">
      <div slot="header" class="clearfix">
        <span>订单支付</span>
      </div>

      <!-- 订单信息 -->
      <el-descriptions title="订单信息" :column="2" border>
        <el-descriptions-item label="订单号">{{ order.orderId }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusType(order.status)">
            {{ getOrderStatusText(order.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="航班号">{{ order.flightNumber }}</el-descriptions-item>
        <el-descriptions-item label="航线">
          {{ order.departureCity }} - {{ order.arrivalCity }}
        </el-descriptions-item>
        <el-descriptions-item label="出发时间">
          {{ formatDateTime(order.departureTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="到达时间">
          {{ formatDateTime(order.arrivalTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="机票类型">{{ order.ticketType }}</el-descriptions-item>
        <el-descriptions-item label="购票数量">{{ order.quantity }}</el-descriptions-item>
        <el-descriptions-item label="总金额">
          <span class="price">¥{{ order.totalAmount }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 支付方式选择 -->
      <div class="payment-method">
        <h3>选择支付方式</h3>
        <el-radio-group v-model="paymentForm.paymentMethod">
          <el-radio-button label="alipay">
            <i class="el-icon-money"></i> 支付宝
          </el-radio-button>
          <el-radio-button label="wechat">
            <i class="el-icon-mobile"></i> 微信支付
          </el-radio-button>
          <el-radio-button label="creditCard">
            <i class="el-icon-bank-card"></i> 银行卡
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 银行卡支付表单 -->
      <div v-if="paymentForm.paymentMethod === 'creditCard'" class="credit-card-form">
        <el-form :model="paymentForm" :rules="rules" ref="paymentForm" label-width="120px">
          <el-form-item label="持卡人姓名" prop="cardHolder">
            <el-input v-model="paymentForm.cardHolder" placeholder="请输入持卡人姓名"></el-input>
          </el-form-item>
          <el-form-item label="银行卡号" prop="cardNumber">
            <el-input v-model="paymentForm.cardNumber" placeholder="请输入16位银行卡号"></el-input>
          </el-form-item>
          <el-form-item label="有效期" prop="expiryDate">
            <el-date-picker
              v-model="paymentForm.expiryDate"
              type="month"
              placeholder="选择有效期"
              format="MM/yyyy"
              value-format="MM/yyyy">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="CVV码" prop="cvv">
            <el-input v-model="paymentForm.cvv" maxlength="3" show-password placeholder="请输入卡背面3位数字"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <!-- 支付按钮 -->
      <div class="payment-action">
        <el-button type="primary" :loading="loading" @click="handlePayment">
          立即支付 ¥{{ order.totalAmount }}
        </el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'PaymentView',
  data() {
    // 银行卡号验证
    const validateCardNumber = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入银行卡号'))
      } else if (!/^\d{16}$/.test(value)) {
        callback(new Error('请输入16位银行卡号'))
      } else {
        callback()
      }
    }

    return {
      order: {},
      loading: false,
      paymentForm: {
        paymentMethod: 'alipay',
        cardHolder: '',
        cardNumber: '',
        expiryDate: '',
        cvv: ''
      },
      rules: {
        cardHolder: [
          { required: true, message: '请输入持卡人姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        cardNumber: [
          { required: true, validator: validateCardNumber, trigger: 'blur' }
        ],
        expiryDate: [
          { required: true, message: '请选择有效期', trigger: 'change' }
        ],
        cvv: [
          { required: true, message: '请输入CVV码', trigger: 'blur' },
          { pattern: /^\d{3}$/, message: '请输入3位数字的CVV码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchOrderDetails()
  },
  methods: {
    async fetchOrderDetails() {
      try {
        const response = await axios.get(`/orders/${this.$route.params.orderId}`)
        if (response.data.code === 0) {
          this.order = response.data.data
        } else {
          this.$message.error(response.data.msg || '获取订单信息失败')
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试')
        console.error('Error fetching order details:', error)
      }
    },
    formatDateTime(datetime) {
      return moment(datetime).format('YYYY-MM-DD HH:mm')
    },
    getOrderStatusType(status) {
      const statusMap = {
        'PENDING': 'warning',
        'PAID': 'success',
        'CANCELLED': 'danger'
      }
      return statusMap[status] || 'info'
    },
    getOrderStatusText(status) {
      const statusMap = {
        'PENDING': '待支付',
        'PAID': '已支付',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    },
    async handlePayment() {
      if (this.paymentForm.paymentMethod === 'creditCard') {
        try {
          await this.$refs.paymentForm.validate()
        } catch (error) {
          return
        }
      }

      this.loading = true
      try {
        const response = await axios.post(`/payments`, {
          orderId: this.order.orderId,
          paymentMethod: this.paymentForm.paymentMethod,
          amount: this.order.totalAmount,
          cardInfo: this.paymentForm.paymentMethod === 'creditCard' ? {
            cardHolder: this.paymentForm.cardHolder,
            cardNumber: this.paymentForm.cardNumber,
            expiryDate: this.paymentForm.expiryDate,
            cvv: this.paymentForm.cvv
          } : null
        })

        if (response.data.code === 0) {
          this.$message.success('支付成功')
          this.$router.push({
            name: 'OrderDetail',
            params: { id: this.order.orderId }
          })
        } else {
          this.$message.error(response.data.msg || '支付失败')
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试')
        console.error('Error processing payment:', error)
      } finally {
        this.loading = false
      }
    },
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.payment-container {
  padding: 20px;
}

.payment-card {
  max-width: 900px;
  margin: 0 auto;
}

.payment-method {
  margin: 30px 0;
}

.credit-card-form {
  max-width: 500px;
  margin: 20px auto;
}

.payment-action {
  text-align: center;
  margin-top: 30px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.el-radio-button {
  margin-right: 15px;
}

.el-icon-money,
.el-icon-mobile,
.el-icon-bank-card {
  margin-right: 5px;
}
</style> 